package com.lh.api.aspect;

import com.lh.common.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @ProjectName: notification
 * @Package: com.hebao.notification.filter
 * @ClassName: WebLogAspect
 * @Description: java类作用描述
 * @Author: xiaohuzi
 * @CreateDate: 2019/2/1 14:39
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/2/1 14:39
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Aspect
@Component
public class WebLogAspect {
    private static   Logger log = LoggerFactory.getLogger(WebLogAspect.class);
    @Pointcut("execution(public * com.lh.api.controller..*.*(..))")
    public void logPointCut() {
        //空方法返回切点
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        try {
            log.info("请求地址 : {}; 请求方式：{};参数 :{}", request.getRequestURL() ,request.getMethod(),
                    Arrays.toString(joinPoint.getArgs()));
        } catch (Exception e) {
            log.info("请求地址 : {}; 请求方式：{}" ,request.getRequestURL(), request.getMethod());
        }
    }

    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        log.info("返回值 : {}", JsonUtils.objectToJson(ret));
    }

}
